package com.sgb.kjwl.view.ui.activity.self.publish;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPackersPublishBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.user.AddPackersEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.self.PackersPublishEvent;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.kjwl.viewmodel.self.publish.PackersPublishModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.NullStringToEmptyAdapterFactory;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/***
 * 工队发布
 */
public class PackersPublishActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;
    private ActivityPackersPublishBinding binding;
    @Inject
    PackersPublishModel viewModel;
    private List<AddressEntity<List<AddressEntity>>> addressEntityList;
    private List<List<AddressEntity>> opt2;
    private int cityPosition1;
    private int cityPosition2;
    private AddPackersEntity addPackersEntity;
    private boolean isUpdate;
    private Gson gson;

    public static void start(Context context) {
        start(context, null);
    }

    public static void start(Context context, Intent extras) {
        Intent intent = new Intent();
        intent.setClass(context, PackersPublishActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(PackersPublishActivity.this, R.layout.activity_packers_publish);
        binding.setViewModel(viewModel);
        binding.itemTvPerson.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.itemTvPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.backView.setOnClickListener(this);
        binding.nextView.setOnClickListener(this);
        binding.itemTvType.setOnWholeItemClickListener(this);
        binding.itemTvArea.setOnWholeItemClickListener(this);
        gson = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
    }

    @Override
    protected void init() {
        opt2 = new ArrayList<>();
    }

    public void showAddressView(List<AddressEntity<List<AddressEntity>>> data) {
        this.addressEntityList = data;
        if (isLoaded) {
            showAddressPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    private void showAddressPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(PackersPublishActivity.this, (options1, options2, options3, v) -> {
            String content = addressEntityList.get(options1).getName() + " "
                    + opt2.get(options1).get(options2).getName();
            binding.itemTvArea.setContent(content);

            cityPosition1 = options1;
            cityPosition2 = options2;
            try {
                viewModel.addPackersEntity.get().setAddress(opt2.get(options1).get(options2).getNo());
                viewModel.addPackersEntity.get().setLocationName(content);
            } catch (Exception e) {

            }
        }).setDecorView(getWindow().getDecorView().findViewById(android.R.id.content)).build();
        businessOption.setPicker(addressEntityList, opt2);
        businessOption.setSelectOptions(cityPosition1, cityPosition2);
        businessOption.show();
    }

    public void showEditView(AddPackersEntity addPackersEntity, boolean isUpdate) {
        this.isUpdate = isUpdate;
        this.addPackersEntity = addPackersEntity;
        viewModel.addPackersEntity.set(addPackersEntity);
        List<String[]> categoryList = addPackersEntity.getCategoryList();
        if (categoryList != null && categoryList.size() > 0) {
            viewModel.typeContent.set("已选择");
        } else {
            viewModel.typeContent.set("");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_view:
                if (!isUpdate) {
                    backSave();
                } else {
                    finish();
                }
                break;
            case R.id.next_view:
                if (viewModel.addPackersEntity.get().getCategoryList() == null || viewModel.addPackersEntity.get().getCategoryList().size() == 0) {
                    Toast.makeText(this, "请选择工队分类", Toast.LENGTH_SHORT).show();
                    return;
                } else if ("".equals(binding.itemTvPerson.getContent()) || binding.itemTvPerson.getContent() == "") {
                    Toast.makeText(this, "请填写队伍规模", Toast.LENGTH_SHORT).show();
                    return;
                } else if (binding.itemTvArea.getContent() == null || binding.itemTvArea.getContent().equals("")) {
                    Toast.makeText(this, "请选择所在地", Toast.LENGTH_SHORT).show();
                    return;
                } else if ("".equals(binding.itemTvTitle.getContent()) || binding.itemTvTitle.getContent() == "") {
                    Toast.makeText(this, "请填写标题", Toast.LENGTH_SHORT).show();
                    return;
                } else if ("".equals(binding.itemTvLinePerson.getContent()) || binding.itemTvLinePerson.getContent() == "") {
                    Toast.makeText(this, "请填写联系人", Toast.LENGTH_SHORT).show();
                    return;
                } else if ("".equals(binding.itemTvLinePerson.getContent()) || binding.itemTvLinePerson.getContent() == "") {
                    Toast.makeText(this, "请填写联系人", Toast.LENGTH_SHORT).show();
                    return;
                } else if ("".equals(binding.itemTvPhone.getContent()) || binding.itemTvPhone.getContent() == "") {
                    Toast.makeText(this, "请填写联系电话", Toast.LENGTH_SHORT).show();
                    return;
                } else if (!CheckUtils.isMobileNum(binding.itemTvPhone.getContent())) {
                    Toast.makeText(this, "请填写正确的联系电话", Toast.LENGTH_SHORT).show();
                    return;
                }
                EventBus.getDefault().postSticky(PackersPublishEvent.make().setMessageTag(EventConstant.EVENT_PUBLISH_PACKERS).setMessageData(viewModel.addPackersEntity.get()));
                PackersPublishNextActivity.start(this);
                break;
        }
    }

    /***
     * 返回保存
     */
    private void backSave() {
        String dataJson = gson.toJson(viewModel.addPackersEntity.get());
        SharedPreferenceUtil.init(this);
        String oldData = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.PACKERS_PUBLISH_DATA, "");
        if ("".equals(oldData) || !dataJson.equals(oldData)) {
            showDialog(dataJson);
        } else {
            finish();
        }
    }

    /***
     * 是否保存
     */
    private void showDialog(String dataJson) {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        if (!this.isFinishing() && !roundCornerDialog.isShowing()) {
            roundCornerDialog.show();
        }
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
//        roundCornerDialog.setOnKeyListener((dialogInterface, i, keyEvent) -> true);//设置点击返回键Dialog不消失

        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        tv_message.setText("是否保存数据");
        //确定
        tv_logout_confirm.setOnClickListener(v -> {
            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.PACKERS_PUBLISH_DATA, dataJson);
            roundCornerDialog.dismiss();
            finish();
        });
        //取消
        tv_logout_cancel.setOnClickListener(v -> {
            roundCornerDialog.dismiss();
            finish();
        });
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.item_tv_type:
                EventBus.getDefault().postSticky(PackersPublishEvent.make().setMessageTag(EventConstant.EVENT_PICK_DEFAULT).setMessageData(viewModel.addPackersEntity.get().getCategoryList()));
                PackersTypeChooicetActivity.start(this);
                break;
            case R.id.item_tv_area:
                if (addressEntityList != null) {
                    showAddressPop();
                } else {
                    viewModel.getAddressModel();
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(PackersPublishEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_PUBLISH_EDIT) {
            String id = (String) event.getMessageData();
            viewModel.getDetailModel(id);
            EventBus.getDefault().removeStickyEvent(event);
        } else if (event.getMessageTag() == EventConstant.EVENT_PICK_TYPE) {
            List<String[]> categoryList = (List<String[]>) event.getMessageData();
            viewModel.addPackersEntity.get().setCategoryList(categoryList);
            if (categoryList.size() > 0) {
                viewModel.typeContent.set("已选择");
            } else {
                viewModel.typeContent.set("");
            }
        } else if (event.getMessageTag() == EventConstant.EVENT_PICK_TYPE_TITLE) {
            String title = (String) event.getMessageData();
            binding.itemTvTitle.setContent(title);
        } else if (event.getMessageTag() == EventConstant.EVENT_PUBLISH_PACKERS_PUBLISH) {
            SharedPreferenceUtil.init(this);
            if (!"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.PACKERS_PUBLISH_DATA, ""))) {
                AddPackersEntity addPackersEntity = gson.fromJson(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.PACKERS_PUBLISH_DATA, ""), AddPackersEntity.class);
                showEditView(addPackersEntity, false);
                EventBus.getDefault().removeStickyEvent(event);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showAddressPop();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        if (addPackersEntity != null && addPackersEntity.getLocationName() != null) {
            String location = null;
            int index = 0;
            if (addPackersEntity != null) {
                location = addPackersEntity.getLocationName();
                index = addPackersEntity.getLocationName().indexOf(" ");
            }
            for (int i = 0; i < addressEntityList.size(); i++) {
                if (addPackersEntity != null && location.substring(0, index).equals(addressEntityList.get(i).getName())) {
                    cityPosition1 = i;
                }
                opt2.add(addressEntityList.get(i).getChildren());
            }
            if (addPackersEntity != null) {
                for (int x = 0; x < opt2.size(); x++) {
                    if (location.substring(index + 1).equals(addressEntityList.get(cityPosition1).getChildren().get(x).getName())) {
                        cityPosition2 = x;
                        break;
                    }
                }
            }
        } else {
            for (int i = 0; i < addressEntityList.size(); i++) {
                opt2.add(addressEntityList.get(i).getChildren());
            }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }
}

